﻿using Kingdee.BOS;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.Metadata.ControlElement;
using Kingdee.BOS.Util;
using System;
using System.ComponentModel;
using Kingdee.BOS.Log;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.WebApi.FormService;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.Permission;
using System.Collections.Generic;
using Kingdee.BOS.BusinessEntity.ThirdSystem;
using Kingdee.BOS.JSON;
using Kingdee.BOS.ServiceHelper.Excel;
using System.Data;
using System.Dynamic;
using System.Threading;

namespace Kingdee.SR.Plugin
{


    [Description("【单据插件】测试下推"), HotUpdate]
    public class TestBillPlugIn : AbstractBillPlugIn
    {
        public override void BarItemClick(BarItemClickEventArgs e)
        {
            base.BarItemClick(e);
            if (e.BarItemKey.EqualsIgnoreCase("xiatui_btn"))
            {
                var showParameter = new DynamicFormShowParameter();

                showParameter.FormId = "AST_FormReturnData";

                showParameter.PageId = Guid.NewGuid().ToString();

                showParameter.ParentPageId = this.View.PageId;

                showParameter.PermissionItemId = PermissionConst.View;

                this.View.ShowForm(showParameter, result =>

                {

                    var list = new List<string>();

                    if (result != null && result.ReturnData != null)

                    {

                        list.Add("方式1返回的数据：" +  result.ReturnData);

                    }


                    if (this.View.Session.ContainsKey("returnData2"))

                    {

                        list.Add("方式2返回的数据：" + this.View.Session["returnData2"]);

                    }

                    this.View.ShowMessage(string.Join("\r\n", list));

                });

            }
        }



    }


    [Description("【表单插件】获取上传内容"), HotUpdate]
    public class DynamicFormReturnDataPlugIn : AbstractDynamicFormPlugIn
    {
        public override void ButtonClick(ButtonClickEventArgs e)
        {
            if (e.Key.EqualsIgnoreCase("F_AST_Btn"))
            {
               
                
            }
        }
    }


    [Description("【表单插件】文件上传"), HotUpdate]

    public class FileUploadFormPlugIn : AbstractDynamicFormPlugIn

    {

        /// <summary>

        /// 文件上传过程中会多次触发自定义事件

        /// </summary>

        /// <param name="e"></param>

        public override void CustomEvents(CustomEventsArgs e)

        {

             base.CustomEvents(e);

            if (e.Key.EqualsIgnoreCase("F_AST_FileUpload"))

            {

                // 设置上传控件参数

                this.View.GetControl("F_AST_FileUpload").SetCustomPropertyValue("NeedCallback", true);

                this.View.GetControl("F_AST_FileUpload").SetCustomPropertyValue("IsRequesting", false);

                if (e.EventName.EqualsIgnoreCase("StateChanged"))
                {
                    JSONObject args =  KDObjectConverter.DeserializeObject<JSONObject>(e.EventArgs);
                    //State说明：0开始上传，1上传中，2上传成功，3上传失败
                    string state = args["State"].GetString();
                    if (state=="0")
                    {
                        this.View.Model.SetValue("F_AST_FileState", "开始上传");
                    }
                    else if (state == "1")
                    {
                        this.View.Model.SetValue("F_AST_FileState", "上传中");
                    }
                    else if (state == "2")
                    {
                        Thread.Sleep(1000);
                        this.View.Model.SetValue("F_AST_FileState", "上传成功");
                        var fileId = this.View.Model.GetValue("F_AST_FileUpload") + "";
                        var filePath = $@"C:\FileUpload\Doc\2025\{fileId}.xlsx";
                        if (System.IO.File.Exists(filePath))
                        {
                            //this.View.ShowMessage(filePath);
                            using (var reader = new ExcelOperation())
                            {
                                var ds1 = reader.ReadFromFile(filePath, 0);
                                var dt = ds1.Tables["Sheet1"];
                                dt.Rows.Remove(dt.Rows[0]);
                                var i = 0;
                                foreach (DataRow row in dt.Rows)
                                {
                                    this.View.Model.CreateNewEntryRow("F_AST_Entity");
                                    this.View.Model.SetValue("F_AST_MaterialNumber", row["Column1"].ToString(), i);
                                    this.View.Model.SetValue("F_AST_QTY", row["Column2"].ToString(), i);
                                    i++;
                                }
                                this.View.ReturnToParentWindow(JsonConvert.SerializeObject(dt));
                                //  this.View.Close();
                                //this.View.ShowMessage(JsonConvert.SerializeObject(dt));
                            }
                        }
                        else
                        {
                            this.View.ShowErrMessage("文件不存在");
                        }
                    }
                    else if (state == "3")
                    {
                        this.View.Model.SetValue("F_AST_FileState", "上传失败");
                    }

                }

                else
                {

                    // 文件上传完毕

                    var postData = KDObjectConverter.DeserializeObject<JSONObject>(e.EventArgs);

                    if (postData != null)

                    {

                        var uploadInfo = new JSONArray(postData["NewValue"].ToString());

                        if (uploadInfo.Count > 0)

                        {

                            // 取上传的文件名

                            var fileInfo = uploadInfo[0] as Dictionary<string, object>;

                            if (fileInfo != null)

                            {

                                var fileName = fileInfo["ServerFileName"].ToString();

                                this.View.Model.SetValue("F_AST_FilePath", fileName);
                                this.View.ShowMessage("文件上传成功，存放路径：" + fileName);

                            }

                        }

                    }

                }

            }

        }

    }
 


}

